package com.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mall.dao.AddressMapper;
import com.mall.entity.Address;
import com.mall.entity.User;
import com.mall.exception.DeleteException;
import com.mall.exception.InsertException;
import com.mall.service.AddressService;
import com.mall.utils.UserCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Transactional
    @Override
    public Integer addAddress(Address address) throws InsertException {
        try {
            User user = UserCache.get();
            address.setCreateTime(new Timestamp(System.currentTimeMillis()));
            address.setUserId(user.getId());
            addressMapper.insert(address);
            return address.getId();
        } catch (Exception e) {
            throw new InsertException("新增收货地址信息异常");
        }
    }

    @Override
    public List<Address> getByUserId(Long userId) {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId,userId);
        List<Address> addressList = addressMapper.selectList(queryWrapper);
        return addressList;
    }

    @Transactional
    @Override
    public void deleteById(Integer id) throws DeleteException {
        try {
            addressMapper.deleteById(id);
        } catch (Exception e) {
            throw new DeleteException("删除地址信息异常");
        }
    }


}